if (files.cwd().endsWith("脚本")) {
  let _require = require;
  require = function (path) {
    if (path.startsWith("./")) {
      path = path.replace("./", "");
    }
    path = files.cwd() + "/gdt_hb/" + path;
    return _require(path);
  }
}

auto.waitFor()
var utils = require("./utils.js");
var storage = storages.create("xiangxiangyuedu");
var time = random(2000, 3000)

function launchAppEnhance(app_name) {
  let thread = threads.start(function () {
    toastLog("检查是否有打开权限!")
    while (true) {
      var allow = text("允许").findOne(5000)
      if (allow) {
        sleep(1000)
        toastLog("发现允许授权!")
        allow.click()
        sleep(1000)
        thread.interrupt()
        break
      }
    }
  })
  sleep(1000)
  var result = launchApp(app_name)
  sleep(3000)
  thread.interrupt()
  return result
}

// 点击控件坐标，控件的clickbale为false的时候
function 点击控件(x) {
  var weight = x.bounds()
  click(weight.centerX(), weight.centerY())
}

function 广告() {
  let try_count = 15, close_btn = null;
  while (!close_btn) {
    if (try_count <= 0) {
      break
    }
    // 直到找到关闭按钮
    close_btn = idContains("ad_close").findOne(1000) ||
      className('android.widget.ImageView').clickable().depth(5).drawingOrder(2).findOne(1000)
    if (close_btn) {
      close_btn.click()
      sleep(time)
      break
    } 
    try_count--
    sleep(3000)
  }
  if(!close_btn){ //没有关闭
    back();
  }
}

function doSwipe(){
  swipe(500,720,64,720,500);
}

function task() {
  var 激励视频 = text('激励视频').findOne(20000)
  if (激励视频) {
    sleep(time)
    var index = 0
    while (index < 4) {
      if(index == 3){//第三个视频之后左滑一段距离
        doSwipe();
        sleep(1000);
      }
      var 完成度 = text('完成度0/1').findOne(1000)
      if (完成度) {
        var finalActivity = currentActivity();
        完成度.parent().parent().click()
        sleep(5000)
        var 首页 = text('首页').findOne(1000)
        if (!首页) {
          toastLog('当前是广告界面')
          utils.waitAdvert(finalActivity);
          sleep(time)
        }
      }else{
        break
      }
      index++
      if(index*25 < 100){
        utils.updateAppProgress(index*25);
      }
    }
  }
}

function main() {
  let open_app = launchAppEnhance("智天下");
  if (open_app) {
    task()
  }
  else {
    toastLog("智天下打开失败，请确认是否安装并授权打开!");
  }
}

try {
  main();
  utils.updateAppProgress(100);
} catch (error) {
  toastLog(error);
}

storage.put("script_running_status", "end");
